package main.controller;

import main.entity.WebUser;
import main.service.WebUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
public class WebUserController {

    @Autowired
    WebUserService webUserService;
    /**
     * 获取全部用户，分页发送
     *
     * @param page
     * @param size
     * @return json [{song1},{song2}..]
     */
    @RequestMapping(value = "/user/get/all/page/{page}/size/{size}", method = RequestMethod.GET)
    public Map<String, Object> getAllUsersInPage(@PathVariable int page, @PathVariable int size) {
        Map<String, Object> resultMap = new HashMap<>();
        Page<WebUser> userPage = webUserService.getAll(PageRequest.of(page, size, Sort.Direction.ASC, "number"));
        resultMap.put("user", userPage.getContent());
        resultMap.put("pages", userPage.getTotalPages());
        resultMap.put("size", userPage.getTotalElements());
        // +1 从 0 开始
        resultMap.put("current", userPage.getNumber() + 1);
        return resultMap;
    }

    /**
     * 获取用户信息
     * @return
     */
    @RequestMapping(value = "/user/current",method = RequestMethod.GET)
    public WebUser getUserById(HttpSession httpSession){
        WebUser webUser = (WebUser) httpSession.getAttribute("user");
        WebUser webUser1 = new WebUser();
        webUser1.setNumber("none");
        if (webUser == null){
            return webUser1;
        }else {
            return webUser;
        }
    }


    /**
     * 更新用户信息
     * @param webUser
     * @return
     */
    @RequestMapping(value = "/user/update/{type}",method = RequestMethod.POST)
    public Map<String,Object> updateUser(WebUser webUser,@PathVariable int type,HttpSession httpSession){
        WebUser sessUser = (WebUser) httpSession.getAttribute("user");
        Map<String,Object> map = new HashMap<>();
        WebUser webUser1 = webUserService.getUserByPk(webUser.getPk());
        if (type == 1){
            webUser1.setPoints(webUser.getPoints());
        }else if (type == 2){
            webUser1.setRank(webUser.getRank());
        }

        if (sessUser == null || !sessUser.getPermission().equals("admin")){
           map.put("result","permission error");
           return map;
        }

        webUser = webUserService.updateUser(webUser1);
        if (webUser == null){
            map.put("result","failed");
        }else {
            map.put("result","success");
        }
        map.put("user",webUser);
        return map;
    }

}
